package com.base.jdbctemplate;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

/**
 * 重写NamedParameterJdbcTemplate中的queryForObject方法，使得返回行数为0时不再抛出异常而是返回null
 */
public class MyNamedParameterJdbcTemplate extends NamedParameterJdbcTemplate {
	
	public MyNamedParameterJdbcTemplate(DataSource dataSource) {
		super(dataSource);
	}
	
	public MyNamedParameterJdbcTemplate(JdbcOperations jdbcOperations) {
		super(jdbcOperations);
	}

	@Override
	public <T> T queryForObject(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper)
			throws DataAccessException {

		List<T> results = getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper);
//		return DataAccessUtils.requiredSingleResult(results);
		return DataAccessUtils.singleResult(results);
	}
}
